<template>
  <view>
    <view v-if="type === 'input' && !disabled" class="cinput" :class="{ redline }">
      <input
        v-model="value"
        :placeholder="placeholder"
        :disabled="disabled"
        :maxlength="maxlength"
        @input="changeInput"
        @blur="blurInput"
      />
      <view v-if="suffix">{{ suffix }}</view>
    </view>
    <view v-if="type === 'input' && disabled" class="cinput">
      <view class="flex-1">{{ value }}</view>
      <view v-if="suffix">{{ suffix }}</view>
    </view>
    <picker
      v-if="type === 'select' && !disabled"
      mode="selector"
      :range="pickerRange"
      :value="selectIndex"
      @change="changePicker"
      @cancel="blurInput"
    >
      <view class="cinput" :class="{ redline }">
        <text>
          {{
            pickerRange && pickerRange.length > selectIndex && selectIndex >= 0
              ? prefix + pickerRange[selectIndex]
              : placeholder
          }}
        </text>
        <view v-if="suffix.length == 2" class="suffix">{{ suffix }}</view>
        <up-icon v-else name="arrow-down" bold />
      </view>
    </picker>
    <view v-if="type == 'select' && otherInputShow" class="cinput">
      <input
        v-model="otherInput"
        placeholder="请输入..."
        :maxlength="maxlength"
        @blur="changeOtherInput"
      />
    </view>
    <view v-if="type === 'select' && disabled" class="cinput">
      <text>
        {{
          pickerRange && pickerRange.length > selectIndex && selectIndex >= 0
            ? prefix + pickerRange[selectIndex]
            : placeholder
        }}
      </text>
      <view v-if="suffix.length == 2" class="suffix">{{ suffix }}</view>
      <up-icon v-else name="arrow-down" bold />
    </view>
    <up-popup v-model:show="checkdShow" :custom-style="customStyle" @maskClick="blurInput">
      <view class="flex justify-between items-center">
        <view class="cancel" @click="cancelCheck">取消</view>
        <view class="checkd-btn" @click="chooseComfirm">完成</view>
      </view>
      <view class="checkd-box">
        <up-checkbox-group v-model="checked" iconPlacement="right" placement="column">
          <up-checkbox
            v-for="(item, index) in pickerRange"
            :key="index"
            :label="item"
            :name="item"
            border-bottom
            active-color="red"
          />
        </up-checkbox-group>
      </view>
    </up-popup>
    <view
      v-if="type == 'checkbox' && !disabled"
      class="cinput"
      :class="{ redline }"
      @click="checkdShow = true"
    >
      {{ value || placeholder }}
    </view>
    <view v-if="type == 'checkbox' && disabled" class="cinput">
      {{ value || placeholder }}
    </view>
    <view v-if="type == 'url' && !disabled" class="cinput" :class="{ redline }" @click="handleUrl">
      <text>
        {{ value ? prefix + value : placeholder }}
      </text>
      <view v-if="suffix" class="suffix">{{ suffix }}</view>
    </view>
    <view v-if="type == 'url' && disabled" class="cinput">
      <text>
        {{ value ? prefix + value : placeholder }}
      </text>
      <view v-if="suffix" class="suffix">{{ suffix }}</view>
    </view>
  </view>
</template>
<script setup>
import { nextTick, ref, watch } from "vue";
const props = defineProps({
  modelValue: {
    // 绑定的数据
    type: [String, Number],
    default: "",
  },
  type: {
    // 类型，input 或 select 或 checkbox 或 url
    type: String,
    default: "input",
  },
  options: {
    // select、checkbox必传
    type: Array,
    default: () => [],
  },
  required: {
    // 是否必填
    type: Boolean,
    default: false,
  },
  redBorder: {
    // 是否检测显示红色边框
    type: Boolean,
    default: false,
  },
  maxlength: {
    type: Number,
    default: 20,
  },
  placeholder: {
    type: String,
    default: "请输入...",
  },
  suffix: {
    type: String,
    default: "",
  },
  prefix: {
    type: String,
    default: "",
  },
  keyValue: {
    type: String,
    default: "",
  },
  keyName: {
    type: String,
    default: "",
  },
  path: {
    // type = url 时必传
    type: String,
    default: "",
  },
  disabled: {
    // 是否禁用
    type: Boolean,
    default: false,
  },
});
const value = ref(props.modelValue);
const pickerRange = ref(); // 选项列表显示字段
const selectIndex = ref(-1);
const otherInputShow = ref(false); // 是否显示其它输入框
const otherInput = ref(""); // 其它输入框的值
const checkdShow = ref(false); // 是否显示弹窗
const checked = ref([]); // 选择的值
const redline = ref(false); // 是否显示红色边框
const customStyle = ref({
  height: "280px",
  borderRadius: "0",
  padding: "20rpx",
  backgroundColor: "#fff",
});
const emit = defineEmits(["update:modelValue", "change"]);

watch(
  () => props.options,
  (newValue) => {
    if (props.keyName) {
      pickerRange.value = newValue.map((item) => item[props.keyName]);
    } else {
      pickerRange.value = newValue;
    }
    if (props.modelValue || props.modelValue >= 0) {
      if (props.type === "checkbox") {
        checked.value = props.modelValue?.split(",");
      } else if (props.type === "select") {
        if (props.keyName) {
          selectIndex.value = newValue.findIndex(
            (item) => item[props.keyValue] == props.modelValue
          );
        } else {
          selectIndex.value = newValue.findIndex((item) => item == props.modelValue);
        }
      }
    }
  },
  {
    immediate: true
  }
);

watch(() => props.modelValue, (newValue) => {
  if (["url", "input"].includes(props.type)) {
    value.value = newValue;
    blurInput()
  }
})

watch(() => props.redBorder, (newValue) => {
  if (newValue) {
    nextTick(() => {
      blurInput()
    });
  }
}, {
  immediate: true
})

watch(() => checkdShow.value, (val) => {
  if (val) {
    checked.value = props.modelValue?.split(",");
  }
})

// 更新 value
const changeInput = (e) => {
  let val = e.detail.value
  emit("update:modelValue", val);
  emit("change", val)
};
// 更新 value
const changePicker = (e) => {
  selectIndex.value = e.detail.value;
  let val = props.options[e.detail.value];
  if (props.keyName) {
    emit("update:modelValue", val[props.keyValue]);
    emit("change", val[props.keyValue])
  } else {
    if (['其它', '其他'].includes(val)) {
      otherInputShow.value = true;
    }
    emit("update:modelValue", val);
    emit("change", val)
  }
  redline.value = false;
};

// 其它输入框
const changeOtherInput = (e) => {
  let val = e.detail.value;
  if (!props.options.includes(val)) {
    pickerRange.value.push(val);
  }
  otherInputShow.value = false;
  nextTick(() => {
    selectIndex.value = pickerRange.value.findIndex((item) => item == val);
    console.log('selectIndex', selectIndex.value);
    value.value = val;
    otherInput.value = "";
    emit("update:modelValue", val);
    emit("change", val)
  });
};

// 失去焦点
const blurInput = () => {
  if (props.required && (props.modelValue == '' || props.modelValue == null || props.modelValue == [])) {
    redline.value = true;
  } else {
    redline.value = false;
  }
};

// 取消选择
const cancelCheck = () => {
  checkdShow.value = false;
  blurInput();
}

// 确认选择
const chooseComfirm = () => {
  value.value = checked.value.join(",");
  if (props.keyName) {
    let list =
      props.options.filter((item) => checked.value.includes(item[props.keyName])) || [];
    emit("update:modelValue", list[props.keyValue]);
    emit("change", list[props.keyValue])
  } else {
    emit("update:modelValue", value.value);
    emit("change", value.value)
  }
  blurInput();
  checkdShow.value = false;
};

// 跳转路由
const handleUrl = () => {
  uni.navigateTo({
    url: props.path,
  });
};
</script>
<style lang="scss" scoped>
.cinput {
  position: relative;
  display: flex;
  border: 2rpx solid #ecebeb;
  align-items: center;
  border-radius: 8rpx;
  padding: 14rpx;
  margin-top: 16rpx;
  font-size: 28rpx;
  background: #fff;
  min-height: 40rpx;
  input,
  text {
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  view {
    padding: 10rpx 6rpx;
    vertical-align: middle;
  }
  .suffix {
    color: #999;
    position: relative;
    &::before {
      content: "";
      position: absolute;
      top: -14rpx;
      left: -14rpx;
      bottom: -14rpx;
      width: 1px;
      background: #ecebeb;
    }
  }
}
.checkd-btn {
  color: #007aff;
  font-size: 17px;
}
.cancel {
  color: #999;
  font-size: 17px;
}
.checkd-box {
  height: 240px;
  margin-top: 20rpx;
  overflow-y: auto;
  .u-checkbox {
    margin: 14rpx 0;
  }
}
.redline {
  border: 2rpx solid red;
}
</style>
